package com.octopus.tree;

import java.util.Date;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;

public class TreeUtils {
	private static final Logger logger = Logger.getLogger(TreeUtils.class
			.getName());

	public static final XMLGregorianCalendar genCurrent() {
		try {
			DateTime dt = DateTime.now();
			DatatypeFactory factory = DatatypeFactory.newInstance();
			XMLGregorianCalendar xmltimestamp = factory
					.newXMLGregorianCalendar();
			xmltimestamp.setYear(dt.getYear());
			xmltimestamp.setMonth(dt.getMonthOfYear());
			xmltimestamp.setDay(dt.getDayOfMonth());
			xmltimestamp.setHour(dt.getHourOfDay());
			xmltimestamp.setMinute(dt.getMinuteOfHour());
			xmltimestamp.setSecond(dt.getSecondOfMinute());
			xmltimestamp.setMillisecond(dt.getMillisOfSecond());
			return xmltimestamp;
		} catch (DatatypeConfigurationException e) {
			logger.error("Date convert from Date to XMLGregorianCalendar", e);
		}
		return null;
	}

	public static final Date convertTo(XMLGregorianCalendar timestamp) {
		if (timestamp == null) {
			return null;
		}
		DateTime datetime = new DateTime(timestamp.getYear(),
				timestamp.getMonth(), timestamp.getDay(), timestamp.getHour(),
				timestamp.getMinute(), timestamp.getSecond(),
				timestamp.getMillisecond());
		return datetime.toDate();
	}

	public static final XMLGregorianCalendar convertTo(Date date)
			throws DatatypeConfigurationException {
		if (date == null) {
			return null;
		}
		DateTime dt = new DateTime(date.getTime());
		DatatypeFactory factory = DatatypeFactory.newInstance();
		XMLGregorianCalendar xmltimestamp = factory.newXMLGregorianCalendar();
		xmltimestamp.setYear(dt.getYear());
		xmltimestamp.setMonth(dt.getMonthOfYear());
		xmltimestamp.setDay(dt.getDayOfMonth());
		xmltimestamp.setHour(dt.getHourOfDay());
		xmltimestamp.setMinute(dt.getMinuteOfHour());
		xmltimestamp.setSecond(dt.getSecondOfMinute());
		return xmltimestamp;
	}
}
